// Package sys
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2024 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
// @AutoGenerate Version 2.13.1
package sys

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"hotgo/internal/dao"
	"hotgo/internal/library/hgorm/handler"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
)

type sSysStockZhAIndex struct{}

func NewSysStockZhAIndex() *sSysStockZhAIndex {
	return &sSysStockZhAIndex{}
}

func init() {
	service.RegisterSysStockZhAIndex(NewSysStockZhAIndex())
}

// Model 指数ORM模型
func (s *sSysStockZhAIndex) Model(ctx context.Context, option ...*handler.Option) *gdb.Model {
	return handler.Model(dao.StockZhAIndex.Ctx(ctx), option...)
}

// List 获取指数列表
func (s *sSysStockZhAIndex) List(ctx context.Context, in *sysin.StockZhAIndexListInp) (list []*sysin.StockZhAIndexListModel, totalCount int, err error) {
	mod := s.Model(ctx)

	// 查询id
	if in.Id > 0 {
		mod = mod.Where(dao.StockZhAIndex.Columns().Id, in.Id)
	}
	mod = mod.WhereIn(dao.StockZhAIndex.Columns().Name, g.Slice{"深证成指", "创业板指", "上证指数", "上证50", "沪深300"})

	totalCount, err = mod.Clone().Count()
	if err != nil {
		err = gerror.Wrap(err, "获取指数数据行失败，请稍后重试！")
		return
	}

	if totalCount == 0 {
		return
	}

	if err = mod.Fields(sysin.StockZhAIndexListModel{}).Page(in.Page, in.PerPage).OrderDesc(dao.StockZhAIndex.Columns().Id).Scan(&list); err != nil {
		err = gerror.Wrap(err, "获取指数列表失败，请稍后重试！")
		return
	}
	return
}

// Edit 修改/新增指数
func (s *sSysStockZhAIndex) Edit(ctx context.Context, in *sysin.StockZhAIndexEditInp) (err error) {
	var res *sysin.StockZhAIndexViewModel
	if err = s.Model(ctx).Where(dao.StockZhAIndex.Columns().Code, in.Code).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取指数失败，请稍后重试！")
		return
	} else {
		if res == nil {
			// 新增
			if _, err = s.Model(ctx, &handler.Option{FilterAuth: false}).
				Fields(sysin.StockZhAIndexUpdateFields{}).
				Data(in).Insert(); err != nil {
				err = gerror.Wrap(err, "新增指数失败失败，请稍后重试！")
			}
		} else {
			// 修改
			if _, err = s.Model(ctx, &handler.Option{FilterAuth: false}).
				Fields(sysin.StockZhAIndexUpdateFields{}).
				Data(in).
				Where(dao.StockZhAIndex.Columns().Code, in.Code).
				Update(); err != nil {
				err = gerror.Wrap(err, "修改指数失败失败，请稍后重试！")
			}
		}
	}
	return
}

// View 获取指数指定信息
func (s *sSysStockZhAIndex) View(ctx context.Context, in *sysin.StockZhAIndexViewInp) (res *sysin.StockZhAIndexViewModel, err error) {
	if err = s.Model(ctx).WherePri(in.Id).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取指数信息，请稍后重试！")
		return
	}
	return
}
